package com.heima.wemedia.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadUtil.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 素材删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPictureMaterial(Integer id) {
        //1.非空判断
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2.根据id查询中间表
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId,id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        //3.判断文章id是否存在，存在不能删除
        if (count>0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"文章有此素材，不能删除");
        }else {
            //4.不存在，删除
            this.removeById(id);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 素材收藏与取消
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collectMaterial(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial.getIsCollection() == WemediaConstants.CANCEL_COLLECT_MATERIAL) {
            wmMaterial.setIsCollection(WemediaConstants.COLLECT_MATERIAL);
            this.updateById(wmMaterial);
        }else {
            wmMaterial.setIsCollection(WemediaConstants.CANCEL_COLLECT_MATERIAL);
            this.updateById(wmMaterial);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1.校验参数
        dto.checkParam();
        //2.开始分页
        IPage page = new Page(dto.getPage(), dto.getSize());
        //3.是否收藏
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //4.根据用户查询
        wrapper.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId());
        //5.时间倒排
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        //6.返回数据
         page= this.page(page,wrapper);
         return new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal(),page.getRecords());
    }

    /**
     * 图片上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        WmMaterial wmMaterial = new WmMaterial();
        //1.判断参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.上传minio
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = multipartFile.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            String file = fileStorageService.uploadImgFile("", fileName + substring, multipartFile.getInputStream());
            //3.保存到数据库
            wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
            wmMaterial.setUrl(file);
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);


        } catch (IOException e) {


        }

        return ResponseResult.okResult(wmMaterial);
    }
}
